﻿using AutoMapper;
using DocumentFormat.OpenXml.Vml.Office;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.Craft;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;


namespace ProduceBasicData.Api.Application.Handler.Material.Craft
{
    public class CreateCraftCommandHandler : IRequestHandler<CreateCraftCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<CraftModel> _craft;
        private readonly IMapper _mapper;
        private readonly ICodeRuleService codeRuleService;

        public CreateCraftCommandHandler(IBaseRespository<CraftModel> craft, IMapper mapper,
            ICodeRuleService codeRuleService)
        {
            _craft = craft;
            _mapper = mapper;
            this.codeRuleService = codeRuleService;
        }

        public async Task<ApiResult<int>> Handle(CreateCraftCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>
            {
                Code = ApiEnum.Success,
                Msg = "新增工艺路线成功"
            };
            DateTime time = DateTime.Now;
            var info = _mapper.Map<CraftModel>(request);

            //编码
            if (string.IsNullOrEmpty(info.CraftNo))
            {
                var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.Inventories.CraftModel");
                if (!string.IsNullOrEmpty(code))
                {
                    info.CraftNo = code;
                }
                else
                {
                    info.CraftNo = $"GY{DateTime.Now:yyyyMMddHHmmss}";
                }
            }

            info.CreateName = request.CreateName;
            info.CreateTime = time;

            if (info != null)
            {
                result.Data = await _craft.AddAsync(info);
            }
            else
            {
                result.Code = ApiEnum.Failed;
                result.Msg = "新增工艺路线失败";
            }

            return await Task.FromResult(result);
        }
    }
}
